//
//  RBCompeDetailListController.m
//  RMMaterialRed
//
//  Created by XBWH on 2024/3/13.
//

#import "RBCompeDetailListController.h"
#import "JXPagerListRefreshView.h"
#import "RBCompeDetailTabHeaderView.h"
#import "RBCompeGameDetailModel.h"
#import "RBCompeRemindModel.h"
#import "RBCompeLiveListController.h"
#import "RBCompeExpListController.h"

@interface RBCompeDetailListController ()
@property(strong,nonatomic)UIView *navBgView;
@property(strong,nonatomic)UILabel *navTitleLabel;
@property(strong,nonatomic)UIButton *backButton;
@property(strong,nonatomic)RBCompeDetailTabHeaderView *compeDetailTabHeaderView;
@property(strong,nonatomic)RBCompeGameDetailModel *compeGameDetailModel;
@property(strong,nonatomic)BRStringPickerView *stringPickerView;
@property(strong,nonatomic)NSMutableArray *collTimeArray;
@end

@implementation RBCompeDetailListController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RBColor(245, 245, 245);
    self.isNeedHeader = YES;
    self.isNeedFooter = YES;
    
    [self rb_loadExpertQueryMatchInfoData];
}
-(void)rb_isShowLeagueListItem:(BOOL)isShowLeague WithMatchInfoDict:(NSDictionary *)matchInfoDict{
    self.titles = @[@"直播",@"指数"];
    
    [self rb_initViewUI];
    [self rb_initNavViewUI];
    
    self.compeGameDetailModel = [RBCompeGameDetailModel mj_objectWithKeyValues:matchInfoDict[@"result"]];
    self.compeGameDetailModel.homeScoresArray = [self.compeGameDetailModel.homeScores mj_JSONObject];
    self.compeGameDetailModel.awayScoresArray = [self.compeGameDetailModel.awayScores mj_JSONObject];
    
    if (RBStringIsEmpty(self.compeGameDetailModel.homeNameZh)) {
        self.compeGameDetailModel.homeNameZh = @"";
    }
    if (RBStringIsEmpty(self.compeGameDetailModel.awayNameZh)) {
        self.compeGameDetailModel.awayNameZh = @"";
    }
    
    self.compeDetailTabHeaderView.compeGameDetailModel = self.compeGameDetailModel;
}
-(void)rb_initViewUI{
    RBCompeDetailTabHeaderView *compeDetailTabHeaderView = [[RBCompeDetailTabHeaderView alloc]initWithFrame:CGRectMake(0, 0, RBScreenWidth, RBScaleWidth(220))];
    MJWeakSelf
    compeDetailTabHeaderView.backButtonTapBlock = ^{
        [weakSelf backButtonTap];
    };
    compeDetailTabHeaderView.collectButtonTapBlock = ^(RBCompeGameDetailModel * _Nonnull compeGameDetailModel) {
        [weakSelf collectBtnTap:compeGameDetailModel];
    };
    self.compeDetailTabHeaderView = compeDetailTabHeaderView;
    self.userHeaderView = compeDetailTabHeaderView;
    self.JXTableHeaderViewHeight = compeDetailTabHeaderView.frame.size.height;
    self.JXheightForHeaderInSection = RBScaleWidth(44);
    self.bottomViewHeight = 0;
    [self prepareCatagoryView];
    self.categoryView.titleLabelAnchorPointStyle = 1;
    self.categoryView.averageCellSpacingEnabled = NO;
    self.categoryView.contentEdgeInsetLeft =0;
    self.categoryView.cellSpacing = 0;
    self.categoryView.cellWidth = RBScreenWidth/(self.categoryView.titles.count);
    self.categoryView.titleColor = RBColor(51, 51, 51);
    self.categoryView.titleFont = RBPingFangFont(15);
    self.categoryView.titleSelectedColor = RBColor(242, 48, 48);
    self.categoryView.titleSelectedFont = RBPingFangMediumFont(15);
    self.categoryView.backgroundColor = [UIColor whiteColor];
    JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
    lineView.indicatorWidth = RBScaleWidth(20);
    lineView.indicatorHeight = RBScaleWidth(4);
    lineView.indicatorColor = RBColor(242, 48, 48);
    self.categoryView.indicators = @[lineView];
    self.pagerView.pinSectionHeaderVerticalOffset = RBNAVIGATION_BAR_HEIGHT;
    self.pagerView.automaticallyDisplayListVerticalScrollIndicator = NO;
    self.pagerView.mainTableView.bounces = NO;
}
-(void)rb_initNavViewUI{
    [self.view addSubview:self.navBgView];
    [self.navBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(RBNAVIGATION_BAR_HEIGHT);
    }];
    [self.navBgView addSubview:self.backButton];
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.navBgView.mas_bottom).mas_equalTo(-RBScaleWidth(10));
        make.left.mas_equalTo(RBScaleWidth(10));
        make.width.height.mas_equalTo(RBScaleWidth(30));
    }];
    [self.navBgView addSubview:self.navTitleLabel];
    [self.navTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.centerY.mas_equalTo(self.backButton.mas_centerY);
    }];
}
-(void)rb_loadExpertQueryMatchInfoData{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"sportId"]=self.sportId;
    dict[@"matchId"]=self.matchId;
    MJWeakSelf
    [RBNetworkTool GET:RBQueryMatchBaseInfoURL parameters:dict success:^(id responseObject) {
        if ([responseObject[@"success"] boolValue]) {
            [weakSelf rb_loadQuerySeasonExpertRankData:responseObject];
        }
    } error:^(id responseObject) {
    } failure:^(NSError *error) {
    }];
}
-(void)rb_loadQuerySeasonExpertRankData:(NSDictionary *)matchInfoDict{
    NSString *seasonId = [NSString stringWithFormat:@"%@",matchInfoDict[@"result"][@"seasonId"]];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"sportId"] = self.sportId;
    dict[@"seasonId"] = seasonId;
    dict[@"userId"] = [RBArchiveTool rb_userModel].userId;
    MJWeakSelf
    [RBNetworkTool GET:RBQuerySeasonExpertRankRowsURL parameters:dict success:^(id responseObject) {
        if ([responseObject[@"success"] boolValue]) {
            if ([responseObject[@"success"] boolValue]) {
                NSArray *leagueArray =responseObject[@"result"];
                if (!RBArrayIsEmpty(leagueArray)) {//联赛排行榜
                    [weakSelf rb_isShowLeagueListItem:YES WithMatchInfoDict:matchInfoDict];
                } else {
                    [weakSelf rb_isShowLeagueListItem:NO WithMatchInfoDict:matchInfoDict];
                }
            }
        }
    } error:^(id responseObject) {
        [weakSelf rb_isShowLeagueListItem:NO WithMatchInfoDict:matchInfoDict];
    } failure:^(NSError *error) {
        [weakSelf rb_isShowLeagueListItem:NO WithMatchInfoDict:matchInfoDict];
    }];
}
- (void)loadAppUserCareUserFollow:(RBCompeGameDetailModel *)model WithUrl:(NSString *)url WithRemindTime:(NSString *)remindTime{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"commonId"] = model.matchId;
    dict[@"sportId"] = self.sportId;
    dict[@"type"] = @"3";
    dict[@"userId"] = [RBArchiveTool rb_userModel].userId;
    if ([model.followStatus intValue]==0&&remindTime.length>0) {
        NSInteger time = [[NSString rb_timeStringIntoYearMonDayTimeStamp:model.matchTime] integerValue] - [remindTime integerValue]*60;
        dict[@"remindTime"] = [NSString rb_timeStampIntoTimeString:[NSString stringWithFormat:@"%ld",time]];
    }
    [RBNetworkTool POST:url parameters:dict success:^(id responseObject) {
        if ([responseObject[@"success"] boolValue]) {
            if ([model.followStatus intValue] == 0) {
                model.followStatus = @"1";
                [RBToast rb_showTopWithText:@"已收藏" topOffset:[[RBTool rb_getCurrentController] RBStatusBarH]+10 duration:1.5 andLeftImage:@"check"];
            }else{
                model.followStatus = @"0";
                [RBToast rb_showTopWithText:@"已取消收藏" topOffset:[[RBTool rb_getCurrentController] RBStatusBarH]+10 duration:1.5 andLeftImage:@"check"];
            }
        }
    } error:^(id responseObject) {
    } failure:^(NSError *error) {
    }];
}
-(void)loadDictInfoData:(RBCompeGameDetailModel *)model{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"code"]=@"match_defore_remind";
    MJWeakSelf
    [RBNetworkTool GET:RBDictInfoURL parameters:dict success:^(id responseObject) {
        if ([responseObject[@"success"] boolValue]) {
            [weakSelf.collTimeArray removeAllObjects];
            NSArray *collTimeArray = [RBCompeRemindModel mj_objectArrayWithKeyValuesArray:responseObject[@"result"]];
            [weakSelf.collTimeArray addObjectsFromArray:collTimeArray];
            [weakSelf rb_showTimeSheetView:model];
        }
    } error:^(id responseObject) {
    } failure:^(NSError *error) {
    }];
}
- (void)pagerView:(JXPagerView *)pagerView mainTableViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat height = floor(RBScaleWidth(220)-RBNAVIGATION_BAR_HEIGHT);
    if (offsetY == height) {
        CGFloat alpha = offsetY / height;
        if (alpha>1) {
            alpha = 1;
        }
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
        self.navBgView.hidden = NO;
        self.navTitleLabel.text = [NSString stringWithFormat:@"%@",self.compeGameDetailModel.competitionName];
    }else{
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        self.navBgView.hidden = YES;
        self.navTitleLabel.text = @"";
    }
}
- (JXPagerView *)preferredPagingView {
    return [[JXPagerListRefreshView alloc] initWithDelegate:self];
}
- (UIView *)tableHeaderViewInPagerView:(JXPagerView *)pagerView {
    return self.userHeaderView;
}

- (NSUInteger)tableHeaderViewHeightInPagerView:(JXPagerView *)pagerView {
    return self.JXTableHeaderViewHeight;
}

- (NSUInteger)heightForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return self.JXheightForHeaderInSection;
}
 - (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index{
     [self.categoryView reloadDataWithoutListContainer];
 }
- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {
    
    NSString *titleStr = self.categoryView.titles[index];
    if ([titleStr isEqualToString:@"直播"]){
        RBCompeLiveListController *compeLiveListVc = [[RBCompeLiveListController alloc] init];
        compeLiveListVc.matchId = self.matchId;
        compeLiveListVc.sportId = self.sportId;
        compeLiveListVc.homeNameZh = self.compeGameDetailModel.homeNameZh;
        compeLiveListVc.awayNameZh = self.compeGameDetailModel.awayNameZh;
        [self.pagerView setListScrollViewToMinContentOffsetY:compeLiveListVc.tableView];
        return compeLiveListVc;
    }else{
        RBCompeExpListController *compeExpListVc = [[RBCompeExpListController alloc] init];
        compeExpListVc.matchId = self.matchId;
        compeExpListVc.sportId = self.sportId;
        compeExpListVc.homeNameZh = self.compeGameDetailModel.homeNameZh;
        compeExpListVc.awayNameZh = self.compeGameDetailModel.awayNameZh;
        [self.pagerView setListScrollViewToMinContentOffsetY:compeExpListVc.tableView];
        return compeExpListVc;
    }
}
-(void)backButtonTap{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)collectBtnTap:(RBCompeGameDetailModel *)compeGameDetailModel{
    if (![RBArchiveTool isLogin]) {
        [[RBOneKeyLogin shareInstance] rb_startLoginWithControllerType:RBOneKeyLoginVcTypeTopVc tabBarItemSelectIndex:1 otherSource:nil];
        return;
    }
    [self rb_showGameRemindPickerView:compeGameDetailModel];
}
-(void)rb_showGameRemindPickerView:(RBCompeGameDetailModel *)model{
    if ([model.followStatus intValue] == 1) {
        [self loadAppUserCareUserFollow:model WithUrl:RBUpcareUserFollowURL WithRemindTime:@""];
    }else{
        [self loadDictInfoData:model];
    }
}
-(void)rb_showTimeSheetView:(RBCompeGameDetailModel *)model{
    NSMutableArray *typeArray = [NSMutableArray array];
    BRStringPickerView *stringPickerView = [[BRStringPickerView alloc] init];
    stringPickerView.pickerMode = BRStringPickerComponentSingle;
    stringPickerView.title = @"设置赛前提醒时间";
    for (RBCompeRemindModel *remindModel in self.collTimeArray) {
        [typeArray addObject:remindModel.name];
    }
    stringPickerView.dataSourceArr = typeArray;
    MJWeakSelf
    stringPickerView.resultModelBlock = ^(BRResultModel *resultModel) {
        RBCompeRemindModel *remindModel = weakSelf.collTimeArray[resultModel.index];
        NSString *valueStr = remindModel.value;
        NSInteger time = [[NSString rb_timeStampIntoTimeString:model.matchTime] integerValue]-[[NSString rb_timeStampIntoTimeString:[NSString rb_getCurrentTime]] integerValue];
        if(time < [valueStr integerValue]*60){
            [MBProgressHUD rb_showAutoMessage:@"赛前时间已经超过" ToView:RBWindow];
            return;
        }
        [weakSelf loadAppUserCareUserFollow:model WithUrl:RBCareUserFollowURL WithRemindTime:valueStr];
    };
    BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
    customStyle.doneTextColor = RBColor(76, 136, 255);
    customStyle.doneTextFont = RBPingFangFont(15);
    customStyle.cancelTextColor = RBColor(51, 51, 51);
    customStyle.cancelTextFont = RBPingFangFont(15);
    customStyle.titleTextFont = RBPingFangMediumFont(15);
    customStyle.titleTextColor = RBColor(51, 51, 51);
    customStyle.topCornerRadius = 10;
    customStyle.rowHeight = RBScaleWidth(48);
    customStyle.pickerHeight = RBScaleWidth(289);
    if (@available(iOS 13.0, *)) {
        customStyle.pickerColor = [UIColor whiteColor];
    } else {
        customStyle.pickerColor = [UIColor whiteColor];
    }
    customStyle.separatorColor = RBColor(204, 204, 204);
    stringPickerView.pickerStyle = customStyle;
    [stringPickerView show];
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.view.frame = CGRectMake(0, 0, RBScreenWidth, RBScreenHeight);
}
- (NSMutableArray *)collTimeArray{
    if (_collTimeArray==nil) {
        _collTimeArray = [NSMutableArray array];
    }
    return _collTimeArray;
}
- (UIView *)navBgView{
    if(_navBgView==nil){
        _navBgView = [[UIView alloc] init];
        _navBgView.backgroundColor = [UIColor whiteColor];
        _navBgView.hidden = YES;
    }
    return _navBgView;
}
-(UILabel *)navTitleLabel{
    if(_navTitleLabel==nil){
        _navTitleLabel = [UILabel rb_labelWithTitle:@"" color:RBColor(51, 51, 51) font:RBPingFangMediumFont(18) alignment:NSTextAlignmentCenter];
    }
    return _navTitleLabel;
}
- (UIButton *)backButton{
    if(_backButton==nil){
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backButton setImage:[UIImage imageNamed:@"backBlack"] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(backButtonTap) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}
@end
